package com.apobates.forum.thrones.controller;

import com.apobates.forum.attention.core.decorater.ForumEntityIcoDecorder;
import com.apobates.forum.core.ImageIOMeta;
import com.apobates.forum.core.entity.BoardGroup;
import com.apobates.forum.core.entity.proxy.BoardGroupReplica;
import com.apobates.forum.core.service.BoardGroupService;
import com.apobates.forum.core.service.BoardService;
import com.apobates.forum.event.elderly.ForumActionEnum;
import com.apobates.forum.member.storage.core.MemberSessionBean;
import com.apobates.forum.thrones.controller.helper.OnlineDescriptor;
import com.apobates.forum.thrones.exception.ResourceNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.CacheControl;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 版块组(卷)控制器
 * 
 * @author xiaofanku
 * @since 20200521
 */
@Controller
@RequestMapping(value = "/board/volumes")
public class BoardGroupController {
    @Autowired
    private BoardGroupService boardGroupService;
    @Autowired
    private BoardService boardService;
    @Autowired
    private ImageIOMeta imageIOMeta;
    
    @GetMapping(path="/{path}.xhtml")
    @OnlineDescriptor(action=ForumActionEnum.BOARD_GROUP_BROWSE)
    public String volumeHome(
            @PathVariable("path") String connectValue,
            MemberSessionBean mbean,
            HttpServletRequest request,
            Model model) {
        BoardGroupReplica bgObj = BoardGroupReplica.of(connectValue).orElseThrow(()->new ResourceNotFoundException("版块组/卷参数解析失败"));
        BoardGroup rs = boardGroupService.get(bgObj.getId()).orElseThrow(()->new ResourceNotFoundException("版块组(卷)不存在或暂时无法访问")); //optional:class java.util.LinkedHashMap cannot be cast to class
        model.addAttribute("boardGroup", rs);
        //版块组下的版块
        model.addAttribute("boardes", boardService.getAllUsedByVolumesId(bgObj.getId()));
        return "default/volumes/index";
    }
    // 查看指定版块组的图标
    @GetMapping(path = "/ico/{id}.png", produces = MediaType.IMAGE_PNG_VALUE)
    public ResponseEntity<byte[]> getBoardVolumeIco(
            @PathVariable("id") int id, 
            @RequestParam(value="scale", required = false, defaultValue = "auto")String scale, 
            HttpServletResponse response,
            Model model) {
        BoardGroup bg = boardGroupService.get(id).orElse(null);
        if (null == bg) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
        try {
            URL boardGroupIcoURL = new ForumEntityIcoDecorder(imageIOMeta.getImageBucketDomain(), imageIOMeta.getUploadImageDirectName())
                    .decode(bg.getImageAddr(), scale)
                    .orElse(null);
            if(null == boardGroupIcoURL){
                boardGroupIcoURL = new URL(String.format("%s/%s/ico/default_icon.png", imageIOMeta.getImageBucketDomain(), imageIOMeta.getUploadImageDirectName()));
            }
            InputStream in = boardGroupIcoURL.openStream();
            byte[] avtarBytes = IOUtils.toByteArray(in);
            
            final HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.setCacheControl(CacheControl.noCache().getHeaderValue());
            return new ResponseEntity<>(avtarBytes, headers, HttpStatus.CREATED);
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            return null;
        }
    }
}